package com.course.system.controller;

import com.course.server.common.PageRequest;
import com.course.server.common.Result;
import com.course.server.dto.RoleDto;
import com.course.server.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;

/**
 * @author: Durian
 * @date: 2021/6/6 14:37
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/admin/roles")
public class RoleController {

    /**
     * 用于日志记录使用
     */
    public static final String BUSINESS_NAME = "角色管理";

    @Resource
    private RoleService roleService;

    @GetMapping
    public Result list(@Validated PageRequest request) {
        return Result.success(roleService.list(request.getPage(), request.getSize()));
    }

    @PostMapping
    public Result save(@RequestBody @Validated RoleDto roleDto) {
        roleService.save(roleDto);
        return Result.success();
    }

    @DeleteMapping("{roleId}")
    public Result delete(@PathVariable("roleId") @NotBlank(message = "待删除角色ID不能为空") String roleId) {
        roleService.delete(roleId);
        return Result.success();
    }

    @PostMapping("/resources")
    public Result saveResources(@RequestBody @Validated RoleDto roleDto) {
        log.info("角色[{}]设置资源权限[{}]", roleDto.getName(), roleDto.getResourceIds());
        roleService.saveResources(roleDto);
        return Result.success();
    }

    @GetMapping("/resources/{roleId}")
    public Result getResources(@PathVariable("roleId") String roleId) {
        return Result.success(roleService.getResources(roleId));
    }

}
